package com.axon.lemon
import grails.converters.JSON;

import com.googlecode.concurrentlinkedhashmap.ConcurrentLinkedHashMap.CatchUpTask;
import com.sun.xml.internal.ws.api.addressing.WSEndpointReference.Metadata

class PlaceController {
    def dataService
    def alert
    def location
    def price1
    def price2
    Vector<String> vFeature
    Vector vProperty
    Vector vType
    List<Integer> vBed
    List<Integer> vBath
    def placeDetail() {
        def IDplace=params.placeID
        //print("placeDetail: "+params.placeID);
        def myPlace=Place.get(IDplace) as Place
        def contact = myPlace.contact as Contact
        def propertytype=myPlace.propertytype as PropertyType
        render([propertytype:propertytype.namePropertyType, address: myPlace.address,price: myPlace.price, description: myPlace.description,bed:myPlace.bed,bath:myPlace.bath,nameContact:contact.nameContact,phoneContact:contact.phoneContact,emailContact:contact.emailContact,image:myPlace.avatar] as JSON)
        
        return
    }
    // search function
    def search(){
        //--------- get loction and prices --------------
        location= params.location
        price1= params.price1
        price2= params.price2
        //--------- get features from page--------------
        vFeature = new Vector<String>()
        def checkedFeatures = params.list('features')
        for(featureResult in checkedFeatures)
        {
            vFeature.add(featureResult)
        }
        //--------- end get features --------------
        //--------- get property from page --------------
        vProperty= new Vector(1,1)
        def checkedProperty = params.list('property')
        for(propertyResult in checkedProperty)
        {
            vProperty.add(propertyResult)
        }
        //--------- end  get property--------------
        //--------- get type from page --------------
        vType= new Vector(1,1)
        def checkedType =params.list('type')
        for(typeResult in checkedType)
        {
            vType.add(typeResult as java.lang.Boolean)
        }
        //--------- get beds from page --------------
        vBed= new ArrayList<Integer>()
        def checkedBed = params.list('beds')
        for(bedResult in checkedBed)
        {
            println bedResult
            vBed.add(bedResult as Integer)
        }
        //--------- end  get beds--------------
        //--------- get baths from page --------------
        vBath= new ArrayList<Integer>()
        def checkedBath = params.list('baths')
        for(bathResult in checkedBath)
        {
            vBath.add(bathResult as Integer)
        }
        
        try {
            if((vFeature.size() == 0) && (vType.size() == 0) && (vProperty.size() ==0) && (vBed.size()==0) && (vBath.size()==0))
            {
                basicSearch();
            }
            else
            {
                advancedSearch();
            }
        } catch (Exception e) {
            print(e)
        }
    
    }
    // search basic
    def basicSearch()
    {
        if((price1=="") || (price2==""))
        {
            def places = Place.createCriteria()
            def results = places.list {
                like("address","%"+location+"%")
            }
            [places:results]
        }
        else
        {
            def places = Place.createCriteria()
            def results = places.list {
                //print(price1.toString());
                like("address","%"+location+"%")
                or {
                    between("price",Float.parseFloat(price1.toString()),Float.parseFloat(price2.toString()))
                }
            }
            [places:results]
        }
    }
    String vBedWhere = ""
    def SQLParams =null
    String vBathWhere = ""
    String vFeatureWhere = ""
    String vTypeWhere = ""
    String vPropertyWhere = ""
    def  checkCondition()
    {
        SQLParams = ["nameFeatureList": vFeature]                
            if(!vProperty.empty){
                vPropertyWhere = " and p.propertytype.namePropertyType in :namePropertyTypeList "
                SQLParams.put("namePropertyTypeList",vProperty)
            }
           if(!vBed.empty){
               vBedWhere = " and p.bed in :bedList  "
               SQLParams.put("bedList",vBed)
           }
           if (!vBath.empty){
               vBathWhere = " and p.bath in :bathList "
               SQLParams.put("bathList",vBath)
           }
           if (!vType.empty){
               vTypeWhere = " and p.buyOrRent in :typeList "
               SQLParams.put("typeList",vType)
           }
    }
    
    // advanced search
    def advancedSearch()
    {
        checkCondition();
        def places = Place.list()
        if(location == "")
        {
            if ((price1 == "") && (price2 ==""))
            {
                // only search advanced
            
                def sql =
                     "select distinct p from  Place p " +
                             "join p.features f " +
                             " where " +
                                     " f.nameFeature in :nameFeatureList " +
                                        vPropertyWhere +
                                      vBedWhere +
                                      vBathWhere +
                                      vTypeWhere +
                    "  "                
                def placesa = Place.executeQuery(sql, SQLParams)            
                [places:placesa]
            }
            else
            {
                // search advanced + price
                
                def sql =
                "select distinct p from  Place p " +
                             "join p.features f " +
                             " where " +
                                     " f.nameFeature in :nameFeatureList " +
                                        vPropertyWhere +
                                      vBedWhere +
                                      vBathWhere +
                                      vTypeWhere +
                                    " and p.price between '"+price1+"' and '"+price2+"' "
           def placesa = Place.executeQuery(sql,SQLParams)        
           [places:placesa]
                
            }
        }
        else
        {
            if((price1 == "") && (price2 ==""))
            {
                // search advanced + location
                def sql =
                "select distinct p from  Place p " +
                    "join p.features f " +
                    " where " +
                        " f.nameFeature in :nameFeatureList " +
                           vPropertyWhere +
                         vBedWhere +
                         vBathWhere +
                         vTypeWhere +
                        " and p.address like '"+"%"+location+"%"+"' "                            
                def placesa = Place.executeQuery(sql,SQLParams)           
            
           [places:placesa]
            }
            else
            {
               //seach advanced + location + price
                def sql =
                "select distinct p from  Place p " +
                    "join p.features f " +
                    " where " +
                        " f.nameFeature in :nameFeatureList " +
                          vPropertyWhere +
                          vBedWhere +
                          vBathWhere +
                          vTypeWhere +
                          " and p.address like '"+"%"+location+"%"+"' " +
                          " and p.price between '"+price1+"' and '"+price2+"' "
                def placesa = Place.executeQuery(sql,SQLParams)
               
                println "placesa: " + placesa
           [places:placesa]
            }
        }
        
       
    }
    def addPlacePage(){
        def a=0;
         a= params.alert;
        if(session.user==null){
            redirect(controller:"index",action:"login")
        }
        else{
            def citylist
            citylist = City.list();//dataService.getCity();
            [citys:citylist,a:a]
            
        }
        
    }
    def doAddPlace(){
        def user=session.user;
        double lat=0;
        double lng=0;
        def price=0;
        def address;
        def description="a";
        def buyOrRent=true;
        def type;
        def bath=0;
        def bed=0;
        def air="";
        def celling="";
        def elevator="";
        def laundry="";
        def parking="";
        def garare="";
        def namect;
        def emailct;
        def phonect;
        def city="";
        def district="";
        
        if((params.tfaddress==null || user==null))
        {
            int i=1;
            redirect (action:"addPlacePage");
        }
        else{
            address=params.tfaddress;
            price=params.tfprice;
            def br=params.cbbbr;
            if(br=="Buy") {buyOrRent=true;}
            else {buyOrRent=false;}
            description=params.tadescrip;
            lat=Double.parseDouble(params.lat);
            
            lng=Double.parseDouble(params.lng);
            
            type=params.cbbtype;
            if(type=="---Choose One---") {type=""}
            city=params.cbbcity;
            district=params.cbbdt;
            if(district=="---Choose One---") {district=""}
            bath=params.tfbathroom;
            bed=params.tfbedroom;
            air=params.air;
            celling=params.celling;
            elevator=params.elevator;
            laundry=params.laundry;
            parking=params.parking;
            garare=params.garare;
            namect=params.tfnamect;
            emailct=params.tfemailct;
            phonect=params.tfphonect;
            def f = request.getFile('image');
            byte[] img = f.getBytes();
            def f1 = request.getFile('files1');
            byte[] img1 = f1.getBytes();
            def f2 = request.getFile('files2');
            byte[] img2 = f2.getBytes();
            def f3 = request.getFile('files3');
            byte[] img3 = f3.getBytes();
            def newplacebasic=dataService.newplacebasic(user,address,price,buyOrRent,description,lat,lng,type,city,district,bath,bed,img)
            if(newplacebasic==0){
                alert=1;
            }
            else{
                def newplacefeature=dataService.newplacefeature(newplacebasic,air,celling,elevator,laundry,parking,garare)
                def newplaceimage=dataService.newplaceimage(newplacebasic,img1,img2,img3)
                def newplacecontact=dataService.newplacecontact(newplacebasic,namect,emailct,phonect)
                    if(newplacefeature==1 && newplaceimage==1 &&newplacecontact==1){
                        alert=3
                    }
                    else{
                        alert=2
                    }
                    
                }
            redirect(action: "addPlacePage", params: [alert: alert])
        
        }
    }
    
    def loaddistrict(){
        def temp = params.idcity;
        def a=City.findByCityName(temp);
        def listDistrict = a ? District.findAllByCity(a) : []
        render listDistrict as JSON
    }

    
    def editPlace(){
		if(!session.user){
			//redirect(action: "../login")
		}
	
	
		def placeID=params.id
		def place=Place.get(placeID)
		def myFeatures = place.features
		def otherFeatures = Feature.list()-myFeatures
		[place:place,types:PropertyType.list(),cities:City.list(),myFeatures:myFeatures,otherFeatures:otherFeatures,districts:District.list()]
		
		
    }
    def doEditPlace(){
        double lat=0;
        double lng=0;
        def price=0;
        def address;
        def description="";
        def buyOrRent=true;
        def type;
        def bath=0;
        def bed=0;
        def air;
        def celling;
        def elevator;
        def laundry;
        def parking;
        def garare;
        def city="";
        def district="";
        
        if((params.tfaddress==null)){}
        else{
            address=params.tfaddress;        //ok
            price=params.tfprice;            //ok
            bath=params.tfbathroom;            //ok
            bed=params.tfbedroom;            //ok
            description=params.tadescrip;    //ok
            def br=params.cbbbr;            //ok
            if(br=="Buy") {buyOrRent=true;}    //ok
            else {buyOrRent=false;}            //ok
            def placeID=params.placeid        //ok
            
            def f = request.getFile('image');
            byte[] img = f.getBytes();
            
            def f1 = request.getFile('files1');
            byte[] img1 = f1.getBytes();
            def f2 = request.getFile('files2');
            byte[] img2 = f2.getBytes();
            def f3 = request.getFile('files3');
            byte[] img3 = f3.getBytes();
            
            def currentPlace = Place.get(placeID)        //ok
            
            currentPlace.bath=Integer.parseInt(bath)    //ok
            currentPlace.bed=Integer.parseInt(bed)        //ok
            currentPlace.description=description        //ok
            currentPlace.price=Double.parseDouble(price)//ok
            currentPlace.buyOrRent=buyOrRent            //ok
            currentPlace.district=District.get(params.district) //ok
            currentPlace.propertytype=PropertyType.get(params.type) //ok
            
            def checkedFeature = params.list('listfeature')
            
            /*
                Delete all features of current place on table: "place_features"
                Add selected features to table: "place_features"
            */
            // Update features for current place
            currentPlace.features.clear()
            for(featureID in checkedFeature){currentPlace.features.add(Feature.get(featureID))}
            
            // Update image(avatar) for current place(change if user pick new image)
            if(img.size()>0){currentPlace.avatar=img}
            
            // Update image(galery) for current place
            
            /*
             Delete all image of current place on table: "Image"
             Add 3 image to table: "Image"
            */
            
            //currentPlace.images.delete()
            /*
            // Delete all image of current place
			def listImages = Image.findAllByPlace(currentPlace)
            for (int i=0; i<listImages.size(); i++){
                Image.get(listImages[i].id).delete()
            }*/
            
            if(img1.size()>0){
                Image objimg1 = new Image()
                objimg1.path = img1
                objimg1.place = currentPlace
                objimg1.save(flush:true)
            }
            if(img2.size()>0){
                Image objimg2 = new Image()
                objimg2.path = img2
                objimg2.place = currentPlace
                objimg2.save(flush:true)
            }
            if(img3.size()>0){
                Image objimg3 = new Image()
                objimg3.path = img3
                objimg3.place = currentPlace
                objimg3.save(flush:true)
            }
            
            // Update Contact
            currentPlace.contact.nameContact=params.tfnamect
            currentPlace.contact.emailContact=params.tfemailct
            currentPlace.contact.phoneContact=params.tfphonect
            
            if(currentPlace.validate()){
                currentPlace.save(failOnError: true)
                redirect(action: "myPlace")
            }else{
                render "Failed"
            }
        }
        //dataService.newplace(address,price,buyOrRent,description,lat,lng,type,city,district,bath,bed,img,air,celling,elevator,laundry,parking,garare,img1,img2,img3)
    }
    
	
	def myPlace(){
		if(session.user){
			def place = Place.where { userprofile == UserProfile.get(session.user.id) && (status==true) }.list()
			[listMyPlaces:place]
		}
		else{
			redirect(controller:"index", action: "login")
		}
    }
    
    def isUser(){
        def testUser=""
        def isMem = session.user
        if (isMem)
            testUser="yes"
            else testUser="no"
            render ([testUser:testUser] as JSON)
        
    }
    def toFavourite(){
        print("coming")
        def ok= true
        def IDplace=params.placeID
        def currentUser = session.user
        def result = Place.get(IDplace)
        def finalResult = new Favourite()
        finalResult.userprofile=currentUser
        finalResult.place=result
        finalResult.save()
        print(result.address)
        render ([ok:ok] as JSON)
    }
    def isFavourite(){
    //    print("vo roy day ")
        def IDplace=params.placeID
        def tempResult
        def currentUser = session.user
    //    print(IDplace+"  in favourite "+currentUser.id)
        def myPlace=Place.get(IDplace)
        def isFavourite = Favourite.findByUserprofileAndPlace(currentUser,myPlace)
    //    print("size of list "+isFavourite.size())
    //    print ("favourite : "+isFavourite.userprofile.fullName)        
        if(isFavourite){
                tempResult = "addTo"
                print ("sau khi add TO")
                }
        else
                tempResult =""
        render([tempResult:tempResult] as JSON)
    }
    def saveComment(){
        try{
            def CM = params.cm
            def placeID=params.placeID
            def placeObject = UserProfile.get(placeID)
            def cm1 = new Comment(content: CM)
            def currentPlace = Place.get(placeID) as Place
            def testID = session.user
            print("new user : " +testID.id)
            print("ten user "+testID.fullName)
            cm1.place=currentPlace
            cm1.userprofile=testID
            cm1.save()
            render ([contentofUSER:CM,userName:testID.fullName,Addres:currentPlace.address] as JSON);
        }catch(Exception e){
            print(e.getMessage())
        }
        return
    }
    def listAllComment(){
        def placeTemp = Place.get(params.placeid)
        print("truoc khi "+placeTemp.address)
        def listOfComment = Comment.findAllByPlace(placeTemp)
        print(listOfComment.size())
        for (int i = 0; i < listOfComment.size(); i++) {
    
            System.out.println(listOfComment[i].content+"  "+listOfComment[i].userprofile.fullName+"  "+listOfComment[i].place.address)
        }
        render  listOfComment as JSON
    }
    
    def liked(){
        def yes = "yes";
        def no="not yet"
        def result
        print("stay at here")
        def placeTemp = Place.get(params.placeid)
        print("address on id place ()"+placeTemp.address)
        def currentUser = session.user
        print("after like "+currentUser)
        def isLiked = LikeNumber.findByUserprofileAndPlace(currentUser,placeTemp)
        if(isLiked) {result = yes
            print("have a address "+isLiked.place.address+" id place "+params.placeid+" id of NumberOfLike "+isLiked.id)
        }
        else  {result = no
            print("not yet")
        }
        render ([result:result] as JSON)
    }
    def allLike(){
        def placeTemp = Place.get(params.placeid)
        def totalOfLike = placeTemp ? LikeNumber.findAllByPlace(placeTemp) : []
        print(totalOfLike.size()+"  " +params.placeid)
        def tempLike = totalOfLike.size()
        render ([totalOfLike:tempLike] as JSON)
    }
	def allLikeInMyPlace(){
		def placeTemp = Place.get(params.placeid)
		def totalOfLike = placeTemp ? LikeNumber.findAllByPlace(placeTemp) : []
		print(totalOfLike.size()+"  " +params.placeid)
		def tempLike = totalOfLike.size()
		render ([totalOfLike:tempLike] as JSON)
	}
    def isLikeUser(){
        def dodgyCount
        print("in ham isLike")
        print(params.testLike+"kiem tra")
        if(params.testLike==true)
        print(params.placeid)
        def placeTemp = Place.get(params.placeid)
        print(placeTemp.address)
        def currentUser = session.user
        def result = new LikeNumber()
        result.place=placeTemp
        result.userprofile=currentUser
        result.save(fush:true)
        def fakePlace = Place.get(params.placeid)
        dodgyCount = LikeNumber.countByPlace(fakePlace)+1
        print ( "khung dien"+dodgyCount)
        render ([totalLike:dodgyCount] as JSON)
    }
    def isDisLikeUser(){
        def dodgyCount
        print("in ham isDisLikeUser")
        print(params.testLike+"kiem tra")
        if(params.testLike==true)
        print(params.placeid)
        def currentUser = session.user
        def placeTemp = Place.get(params.placeid)
        print(placeTemp.address)
        // test lan ni thoy
        def afterDislike = LikeNumber.findByUserprofileAndPlace(currentUser,placeTemp)
        afterDislike.delete(flush:true)
        dodgyCount = LikeNumber.countByPlace(placeTemp)
        print("sau khi xoa "+dodgyCount)
        render ([disLike:dodgyCount] as JSON)
    }
    def isRemovePlace(){
        print("coming???")
        def placeID = params.testid
        print("id cua thang remove "+placeID)
        def placeTemp = Place.get(placeID)
        def currentUser = session.user
    //    def resultOfPlace = Favourite.get(placeID)
        def resultOfPlace = Favourite.findByUserprofileAndPlace(currentUser,placeTemp)
        resultOfPlace.delete(flush:true)
        render ([ok:"nhamnhi"] as JSON)
    }
    def delete(){
        def placeID=params.placeID
        def place=Place.get(placeID)
        print(place);
        def status=place.status=false
        place.save(flush:true)
        
        print(status)
        
    }
	// nguyen
	def isLikeInMyPlace(){
		def dodgyCount
		if(params.testLike==true)
		print(params.placeid)
		def currentUser = session.user
		def placeTemp = Place.get(params.placeid)
		print(placeTemp.address)
		def result = new LikeNumber()
		result.place=placeTemp
		result.userprofile=currentUser
		result.save(fush:true)
		def fakePlace = Place.get(params.placeid)
		dodgyCount = LikeNumber.countByPlace(fakePlace)+1
		render ([totalLike:dodgyCount] as JSON)
	}
	def isDisLikeInMyPlace(){
		def dodgyCount
		def currUser = UserProfile.get(session.user.id)
		def placeTemp = Place.get(params.placeid)
		def afterDislike = LikeNumber.findByUserprofileAndPlace(currUser,placeTemp)
		if(afterDislike){
			afterDislike.delete(flush:true)
			dodgyCount = LikeNumber.countByPlace(placeTemp)
			render ([disLike:dodgyCount] as JSON)
		}
	}
	def saveCommentInMyPlacePage(){
		try{
			def CM = params.cm
			def usrID = session.user
			def placeID=params.placeID
			def placeObject = UserProfile.get(placeID)
			def cm1 = new Comment(content: CM)
			def currentPlace = Place.get(placeID) as Place
			cm1.place=currentPlace
			cm1.userprofile=usrID
			cm1.save()
			render ([userName:usrID.fullName,Addres:currentPlace.address] as JSON);
		}catch(Exception e){
			print(e.getMessage())
		}
	}
	def listImage(){
		def IDplace=params.placeID
		def placeI=Place.get(IDplace)
		def listimage= Image.findAllByPlace(placeI)
		render listimage as JSON;
	}
	def showImage(){
		def IDplace= params.placeID
		int index = Integer.parseInt(params.index)
		def placeI=Place.get(IDplace)
		def listimage= Image.findAllByPlace(placeI)
		response.outputStream << listimage.get(index).path
	}
    // nguyen 
}